﻿#region License, Terms and Conditions
//
// Copyright (c) 2008, aspZone.com
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the <organization> nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY aspZone.com ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author(s):
//  John Rudolf Lewis (http://aspZone.com)
//
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Iesi.Collections.Generic;
using aspZone.Commerce.Service;

namespace aspZone.Commerce.Model
{
    public class Order
    {   
        private IList<OrderItem> items;
        private IList<Transaction> transactions;

        public Order()
        {
            this.Id = 0;
            this.DateCreated = DateTime.Now;
            this.OrderStatus = OrderStatus.NotCheckoutOut;

            this.items = new List<OrderItem>();
            this.transactions = new List<Transaction>();

            this.ShippingCalculator = new DefaultShippingCalculator();
        }

        public virtual IShippingCalculator ShippingCalculator { get; set; }

        /// <summary>
        /// Gets the primary key
        /// </summary>
        public virtual int Id { get; private set; }

        /// <summary>
        /// Gets the status of the order
        /// </summary>
        public virtual OrderStatus OrderStatus { get; private set; }

        /// <summary>
        /// Gets the date that the order was created
        /// </summary>
        public virtual DateTime DateCreated { get; private set; }

        /// <summary>
        /// Gets or sets the date that the order was shipped
        /// </summary>
        public virtual DateTime? DateShipped { get; set; }

        /// <summary>
        /// Gets or sets the billing address
        /// </summary>
        public virtual Address BillingAddress { get; set; }
        
        /// <summary>
        /// Gets or sets the shipping address
        /// </summary>
        public virtual Address ShippingAddress { get; set; }

        /// <summary>
        /// Gets a readonly list of OrderItems
        /// </summary>
        public virtual IList<OrderItem> Items
        {
            get
            {
                return this.items.ToList().AsReadOnly();
            }
        }

        /// <summary>
        /// Gets a list of transactions 
        /// </summary>
        public virtual IList<Transaction> Transactions
        {
            get
            {
                return this.transactions;
            }
        }

        /// <summary>
        /// Adds a product to the order
        /// </summary>
        /// <param name="product"></param>
        public virtual void AddItem(Product product)
        {
            AddItem(product, 1);
        }

        /// <summary>
        /// Adds a product to the order
        /// </summary>
        /// <param name="product">the product to add to the order</param>
        /// <param name="quantity">the quantity</param>
        public virtual void AddItem(Product product, int quantity)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product", "product must not be null");
            }

            if (quantity <= 0)
            {
                throw new ArgumentOutOfRangeException("quantity", "quantity must be greater than 0");
            }

            if (product.QuantityAvailable < quantity)
            {
                throw new ArgumentOutOfRangeException("product", "product does not have enough quantity available");
            }

            var orderItem = FindItem(product);
            if (orderItem != null)
            {
                orderItem.Quantity += quantity;
            }
            else
            {
                this.items.Add(new OrderItem(product, quantity));
            }
            this.ReCalculateTotal();
        }

        /// <summary>
        /// Adjusts the quantity of the specified product in the order
        /// </summary>
        /// <param name="product">the product for which to adjust quantity</param>
        /// <param name="quantity">the quantity</param>
        public virtual void AdjustQuantity(Product product, int quantity)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product", "product must not be null");
            }

            if (product.QuantityAvailable < quantity)
            {
                throw new ArgumentOutOfRangeException("product", "product does not have enough quantity available");
            }

            var orderItem = FindItem(product);
            if (orderItem != null)
            {
                if (quantity > 0)
                {
                    orderItem.Quantity = quantity;
                }
                else
                {
                    this.RemoveItem(product);
                }
                this.ReCalculateTotal();
            }
        }

        /// <summary>
        /// Removes the specified product from the order
        /// </summary>
        /// <param name="product">the product to be removed</param>
        public virtual void RemoveItem(Product product)
        {
            var orderItem = FindItem(product);
            if (orderItem != null)
            {
                this.items.Remove(orderItem);
                this.ReCalculateTotal();
            }
        }

        /// <summary>
        /// Removes all products from the order
        /// </summary>
        public virtual void Clear()
        {
            this.items.Clear();
            this.ReCalculateTotal();
        }

        /// <summary>
        /// Finds the specified product in the order
        /// </summary>
        /// <param name="product">the product to find</param>
        /// <returns>the OrderItem for the product if found, otherwise null</returns>
        public virtual OrderItem FindItem(Product product)
        {
            return this.items.SingleOrDefault(x => x.Product.Equals(product));
        }

        /// <summary>
        /// Gets the SubTotal for the order
        /// </summary>
        public virtual decimal SubTotal { get; private set; }

        /// <summary>
        /// Gets the dollar amount of shipping and handling for this order
        /// </summary>
        public virtual decimal ShippingAndHandling { get; private set; }

        /// <summary>
        /// Gets the total dollar amount for this order
        /// </summary>
        public virtual decimal Total { get; private set; }

        private void ReCalculateTotal()
        {
            this.SubTotal = this.items.Sum(x => x.SubTotal);
            this.ShippingAndHandling = this.ShippingCalculator.CalculateShipping(this);
            this.Total = this.SubTotal + this.ShippingAndHandling;
        }

        #region Object overrides

        public override bool Equals(object obj) {
            if (obj is Order) {
                Order compareTo = (Order)obj;
                return compareTo.Id == this.Id;
            } else {
                return base.Equals(obj);
            }
        }

        public override string ToString() {
            return "Order Id: " + this.Id.ToString();
        }

        public override int GetHashCode() {
            return this.Id.GetHashCode();
        }
        #endregion

    }
}
